<template>
    <el-collapse-item title="数据来源（预览生效）" name="request" class="request-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="URL请求" name="first">
                <el-form>
                    <el-form-item label="请求地址">
                        <el-input v-model.trim="request.url" @blur="validateURL">
                            <template slot="prepend">HTTPS://</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="请求方法">
                        <el-select v-model="request.method">
                            <el-option v-for="item in methodOptions" :key="item" :label="item" :value="item">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="请求参数">
                        <el-select v-model="request.paramType" placeholder="参数类型" @change="onChnage">
                            <el-option v-for="item in dataOptions" :key="item" :label="item" :value="item">
                            </el-option>
                        </el-select>
                        <div v-if="request.paramType === 'array'" class="param-container">
                            <p>数据项</p>
                            <div v-for="(item, index) in request.data" :key="index" class="div-delete">
                                <el-input v-model="request.data[index]" placeholder="请输入参数值"></el-input>
                                <span class="iconfont icon-shanchu" @click="deleteData(index)"></span>
                            </div>

                            <el-button @click="addArrayData">添加</el-button>
                        </div>
                        <div v-else-if="request.paramType === 'string' || request.paramType === 'object'"
                            class="param-container">
                            <p>数据项</p>
                            <div v-for="(item, index) in request.data" :key="index" class="param-object-container">
                                <el-input v-model="item[0]" placeholder="参数名"></el-input>
                                <el-input v-model="item[1]" placeholder="参数值"></el-input>
                                <span class="iconfont icon-shanchu" @click="deleteData(index)"></span>
                            </div>
                            <el-button @click="addData">添加</el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="定时触发">
                        <el-switch v-model="request.series"></el-switch>
                        <template v-if="request.series">
                            <p>触发间隔（毫秒）</p>
                            <el-input v-model="request.time" type="number"></el-input>
                            <p>触发次数（0 为无限）</p>
                            <el-input v-model="request.requestCount" type="number"></el-input>
                        </template>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="数据库" name="second">
                <el-form>
                    <el-form-item label="是否需要表链接">
                        <el-switch v-model="isTable" active-text="是" inactive-text="否" @change="changeStatus">
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="链表" v-if="isTable">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="addTable">新增</el-button>
                    </el-form-item>
                    <div v-if="!isTable">
                        <el-form-item label="请选择表">
                            <el-select v-model="tableName" placeholder="请选择" @change="changTable">
                                <el-option v-for="(item, index) in options" :key="index" :label="item.TABLE_COMMENT"
                                    :value="item.TABLE_NAME">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请选择字段">
                            <el-select v-model="fieldName" multiple placeholder="请选择" @change="changcolumn">
                                <el-option v-for="item in columnOptions" :key="item.value" :label="item.columnComment"
                                    :value="item.columnName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div v-else v-for="(item, index) in tableNameList" :key="index">
                        <el-form-item label="请选择表">
                            <el-select v-model="item.tableName" placeholder="请选择"
                                @change="(value) => changTableMany(value, index)">
                                <el-option v-for="(item, index) in options" :key="index" :label="item.TABLE_COMMENT"
                                    :value="item.TABLE_NAME">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请选择字段">
                            <el-select v-model="item.fieldName" multiple placeholder="请选择"
                                @change="(value) => changcolumnMany(value, index)">
                                <el-option v-for="item in columnOptions" :key="item.value" :label="item.columnComment"
                                    :value="item.columnName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="请选择连接字段">
                            <el-select v-model="item.connectField" placeholder="请选择">
                                <el-option v-for="item in columnOptions" :key="item.value" :label="item.columnComment"
                                    :value="item.columnName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button type="danger" size="mini" @click="delTable(index)">删除</el-button>
                        </el-form-item>
                        <el-divider></el-divider>
                    </div>
                    <el-button v-if="isTable" type="primary" @click="generateSql">查询</el-button>
                    <el-button v-if="isTable" type="danger" @click="cleanSql">重置</el-button>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="固定数据源" name="three">
                <el-form>
                    <el-form-item label="请选择表">
                        <el-select v-model="value" placeholder="请选择">
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>
    </el-collapse-item>
</template>

<script>
import { column, create } from 'mathjs';
import { urlRE, getURL } from '../../utils/request'
import { getTables, getTablesColumns, getExecuteQuery } from '../../../../api/table/index'
export default {
    props: {
        requestData: {
            type: Object,
            required: true,
            default: () => { },
        }
    },
    data() {
        return {
            mysqlName: "",
            activeName: "second",
            fieldName: [],
            fieldName2: [],
            tableName2: "",
            tabelsList: [],
            value: "",
            options: [],
            options2: [],
            tableName: "",
            tableNameList: [],
            columnFont: "",
            result: [],
            columnOptions: [],
            columnOptions2: [],
            resultLike: "",
            isTable: false,
            methodOptions: [
                'GET',
                'POST',
                'PUT',
                'DELETE',
            ],
            dataOptions: [
                'object',
                'array',
                'string',
            ],
        }
    },
    computed: {
        request() {
            return this.$store.state.curComponent.request
        },
    },
    watch: {
        // "requestData"() {
        //     getTables({
        //         database: this.requestData.mysql.mysqlName
        //     }).then(response => {
        //         // this.userList.push(response.data.user)
        //     });
        // }
    },
    created() {
        if (this.request.mysql.mysqlName != "") {
            getTables({
                database: this.request.mysql.mysqlName
            }).then(response => {
                this.options = response
            });
        }
        this.isTable = this.$store.state.curComponent.propValue.isTable
        if (this.$store.state.curComponent.request.mysql.tableName != "") {
            this.tableName = this.$store.state.curComponent.request.mysql.tableName
        }

        if (this.$store.state.curComponent.request.mysql.fieldName.length > 0) {
            this.fieldName = this.$store.state.curComponent.request.mysql.fieldName
        }


    },
    methods: {
        /**
         * 新增一个表链接
         */
        addTable() {
            this.tableNameList.push({
                tableName: '',
                fieldName: [],
                connectField: '',
                filedhistory: []
            })
        },
        cleanSql () {
            this.tableNameList = []
            this.$store.state.curComponent.request.mysql.tableNameList = []
            this.$store.state.curComponent.propValue.columns = []
        },
        /**
         * 删除一个表连接
         */
        delTable(index) {
            this.tableNameList.splice(index, 1)
        },
        /**
         * 获取表的字段名称
         */
        getTablesColumnsFont(index) {
            getTablesColumns({
                database: this.request.mysql.mysqlName,
                table: this.tableName
            }).then(response => {
                if (!this.isTable) {
                    this.columnOptions = response
                } else {
                    this.tableNameList[index].filedhistory = response
                    this.columnOptions = response
                    console.log(this.tableNameList)
                }

            });
        },
        changTableMany(value, index) {
            this.tableName = value
            this.$store.state.curComponent.request.mysql.tableName = this.tableName
            this.getTablesColumnsFont(index)
        },
        changeStatus(val) {
            this.$store.state.curComponent.propValue.isTable = val
        },
        selectMysql() {
            getTables({
                database: this.requestData.mysql.mysqlName
            }).then(response => {
                this.options = response
                this.generateSql()
            });
        },
        addArrayData() {
            this.request.data.push('')
        },

        addData() {
            this.request.data.push(['', ''])
        },

        deleteData(index) {
            this.request.data.splice(index, 1)
        },

        onChnage() {
            if (this.request.paramType === 'array') {
                this.request.data = ['']
            } else {
                this.request.data = [['', '']]
            }
        },

        validateURL() {
            const url = this.request.url
            if (url && /^\d+$/.test(url) || !urlRE.test(getURL(url))) {
                this.$message.error('请输入正确的 URL')
            }
        },

        /**
         * 选择表
         */
        changTable(val) {
            // console.log(val)
            this.tableName = val
            this.$store.state.curComponent.request.mysql.tableName = this.tableName
            this.getTablesColumnsFont()
        },

        /**
         * 选择字段
         * @param val 
         */
        changcolumn(val) {
            this.fieldName = val
            let columns = []
            for (let i in this.fieldName) {
                const column = this.columnOptions.find(res => res.columnName === this.fieldName[i]);
                columns.push({
                    prop: this.fieldName[i],
                    label: column && column.columnComment != "" ? column.columnComment : column.columnName
                })
            }
            this.$store.state.curComponent.request.mysql.fieldName = this.fieldName
            this.$store.state.curComponent.propValue.columns = columns
            this.generateSql()
        },

        /**
         * 多表字段选择整合table字段显示
         */
        changcolumnMany(value, index) {
            console.log(value, index)
            let columns = []
            for (let i in this.tableNameList) {
                let data = this.tableNameList[i].fieldName
                for (let j in data) {
                    const column = this.tableNameList[i].filedhistory.find(res => res.columnName === data[j]);
                    columns.push({
                        prop: data[j],
                        label: column && column.columnComment != "" ? column.columnComment : column.columnName
                    })
                }
            }
            this.$store.state.curComponent.request.mysql.tableNameList = this.tableNameList
            this.$store.state.curComponent.propValue.columns = columns
            // if (this.tableNameList.length > 1) {
            //     this.generateSQLCreate();
            // }
        },

        /**
         * 处理生成多表得相同字段供用户去选择关联得字段
         */
        generateSQLCreate(tableNameList) {

            let baseQuery = `SELECT `;
            let fromClause = ` FROM `;
            let whereClause = ` WHERE `;

            tableNameList.forEach((table, index) => {
                // 添加要查询的字段
                table.fieldName.forEach((field, fieldIndex) => {
                    baseQuery += `${table.tableName}.${field}`;
                    if (index < tableNameList.length - 1 || fieldIndex < table.fieldName.length - 1) {
                        baseQuery += `, `;
                    }
                });

                // 添加表名
                fromClause += `${table.tableName}`;
                if (index < tableNameList.length - 1) {
                    fromClause += `, `;
                }

                // 添加连接条件
                if (index < tableNameList.length - 1) {
                    whereClause += `${table.tableName}.${table.connectField} = ${tableNameList[index + 1].tableName}.${tableNameList[index + 1].connectField}`;
                    if (index < tableNameList.length - 2) {
                        whereClause += ` AND `;
                    }
                }
            });

            // 拼接完整的 SQL 语句
            let sqlQuery = baseQuery + fromClause + whereClause;
            return sqlQuery;
        },


        /**
         * 选择关联字段
         */
        changTableList(val, val2) {
            console.log(val, val2)
            const result = val.filter(item1 => {
                // 在 array2 中查找 columnName 相同的对象
                return val2.some(item2 => item2.columnName === item1.columnName);
            }).map(item => ({
                columnName: item.columnName,
                columnComment: item.columnComment // 只取第一个数组中的 columnComment
            }));

            return result;
        },
        /**
         * 生成sql语句
         */
        generateSql() {
            console.log(this.$store.state.curComponent.propValue);
            let fields = [];
            let sql = "";

            if (this.isTable) {
                if (this.tableNameList.length <= 1) {
                    this.$message.error('链表查询至少两张表');
                    return;
                }
                sql = this.generateSQLCreate(this.tableNameList)
            } else {
                // Single table query
                fields = this.fieldName.map(field => `${this.tableName}.${field}`).join(", ");
                sql = `SELECT ${fields} FROM ${this.tableName}`;
            }
            getExecuteQuery({
                sql: sql,
                pageNum: 1,
                pageSize: 10
            }).then(response => {
                this.$store.state.curComponent.propValue.data = response.records
                this.$store.state.curComponent.propValue.total = response.total
                this.$store.state.curComponent.propValue.sql = sql
            });
        },
        handleClick() { },
    },
}
</script>

<style lang="scss" scoped>
.request-container {
    .param-container {
        margin-top: 10px;

        .el-button {
            margin-top: 10px;
        }

        .param-object-container {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 4px;

            .el-input {
                width: 98px;
            }

            .el-button {
                margin: 0;
                margin-left: 8px;
            }
        }

        .div-delete {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 4px;

            .el-button {
                margin: 0;
                margin-left: 8px;
            }
        }
    }

    .icon-shanchu {
        cursor: pointer;
        margin-left: 10px;
    }
}
</style>
